import os
import subprocess
import re
import shutil

# component_links = """
# https://doc.quickapp.cn/widgets/a.html
# https://doc.quickapp.cn/widgets/div.html
# https://doc.quickapp.cn/widgets/image.html
# https://doc.quickapp.cn/widgets/input.html
# https://doc.quickapp.cn/widgets/label.html
# https://doc.quickapp.cn/widgets/list.html
# https://doc.quickapp.cn/widgets/map.html
# https://doc.quickapp.cn/widgets/option.html
# https://doc.quickapp.cn/widgets/picker.html
# https://doc.quickapp.cn/widgets/popup.html
# https://doc.quickapp.cn/widgets/progress.html
# https://doc.quickapp.cn/widgets/rating.html
# https://doc.quickapp.cn/widgets/richtext.html
# https://doc.quickapp.cn/widgets/select.html
# https://doc.quickapp.cn/widgets/slider.html
# https://doc.quickapp.cn/widgets/span.html
# https://doc.quickapp.cn/widgets/stack.html
# https://doc.quickapp.cn/widgets/swiper.html
# https://doc.quickapp.cn/widgets/switch.html
# https://doc.quickapp.cn/widgets/tabs.html
# https://doc.quickapp.cn/widgets/tab-bar.html
# https://doc.quickapp.cn/widgets/tab-content.html
# https://doc.quickapp.cn/widgets/text.html
# https://doc.quickapp.cn/widgets/textarea.html
# https://doc.quickapp.cn/widgets/video.html
# """
# css_links = """
# https://doc.quickapp.cn/widgets/common-styles.html
# """

def is_quickapp_code(code):
    # 使用正则表达式检查字符串中是否包含指定的HTML标签
    template_tag = re.search(r'<template>.*?</template>', code, re.DOTALL)
    script_tag = re.search(r'<script>.*?</script>', code, re.DOTALL)
    style_tag = re.search(r'<style>.*?</style>', code, re.DOTALL)

    # 如果所有标签都存在，则返回True
    if template_tag or script_tag or style_tag:
        return True
    else:
        return False

def get_exist_ux_code(target_file):
    if not is_ux_exist(target_file):
        print(f"{target_file} 不存在")
        return ""
    try:
        with open(target_file, 'r', encoding='UTF-8') as file:
            return file.read()
    except Exception as e:
        print(e)

def is_ux_exist(file_path):
    print(f"is_ux_exist: {file_path}")
    print(f"is_ux_exist: {os.path.exists(file_path)}")
    return os.path.exists(file_path)

def write_result_to_ux(target_file, code_result):
    
    pattern_template = r'(<template>.*?</template>)'
    pattern_script = r'(<script>.*?</script>)'
    pattern_style = r'(<style>.*?</style>)'
    template_new = ""
    script_new = ""
    style_new = ""
    if code_result:
        template_new = re.search(pattern_template, code_result, re.DOTALL).group(1)
        script_new = re.search(pattern_script, code_result, re.DOTALL).group(1)
        style_new = re.search(pattern_style, code_result, re.DOTALL).group(1)
    # print(f"template_new\n{template_new}")
    # print(f"script_new\n{script_new}")
    # print(f"style_new\n{style_new}")

    exist_ux_code = get_exist_ux_code(target_file)
    # print(f"exist_ux_code\n{exist_ux_code}")
    template_exist = template_new
    script_exist = script_new
    style_exist = style_new
    if exist_ux_code:
        template_exist = re.search(pattern_template, exist_ux_code, re.DOTALL).group(1)
        script_exist = re.search(pattern_script, exist_ux_code, re.DOTALL).group(1)
        style_exist = re.search(pattern_style, exist_ux_code, re.DOTALL).group(1)

    with open(target_file, 'w', encoding='utf-8') as file:
        file.write(template_exist + '\n\n')
        file.write(script_exist + '\n\n')
        file.write(style_exist + '\n\n')

def reconstruct_import(code):
    return code

def copy_template(source_directory, target_directory):
    if not os.path.exists(os.path.dirname(target_directory)):
        os.makedirs(os.path.dirname(target_directory))
    shutil.copytree(source_directory, target_directory, dirs_exist_ok=True)

def read_txt(file_path):
    with open(file_path, 'r', encoding='UTF-8') as file:
        return file.read()
    
def get_h5_code(h5_code_path):
    h5_code = read_txt(h5_code_path)
    # print(h5_code)
    return h5_code

def get_direct_prompt(task):
    component_usage_path = os.path.join(os.getcwd(), 'component_and_css_rules.txt')
    component_usage = read_txt(component_usage_path)
    direct_prompt = f"""
        {task}
        To compelete the task, you need to learn the development standards of Quickapp, including components, styles, etc., and then completely use the Quickapp development standards for code generation。
        The format of the Quickapp page is:
        <import name="xx" src="xx"></import>
        <template>
            <tags>
        </template>
        <script>
            export default {{
                data() {{
                    return {{}}
                }},
                xxx() {{}}
            }}
        </script>
        <style>
            css
        </style>
        - Note that tags and styles supported by Quickapp standards must be used. for example:
            （1）The <button> tag is not supported, instead use <input type="button"></input> instead.
            （2）The <button> tag is not supported, instead use <input type="button"></input> instead.
            （3）Text cannot be written directly inside <div></div>, but <text></text> should be used.
            （4）You cannot use <br> or \n for text line breaks. Instead, use multiple <text></text>.
            （5）<span> can only be used as a child component of <text>, <a> and <span>
            （6）Standards related to wechat miniprogram cannot appear. For example <view></view>
            （7）The standard of vue.js cannot appear. For example, Quickapp methods are at the same level as data, rather than appearing in methods.
            （8）CSS style length only supports px and % units, and does not support dp, rem, rpx and other units.
            （9）External styles can be introduced
            （10）Pay attention to converting the writing method of introducing custom components into vuejs into the writing method of introducing custom components into Quickapp:
                <import name="child" src="../components/child.ux"></import>
                <template>
                <div class="container">
                    <child></child>
                </div>
                </template>
                Pay attention, the above <import> statement needs to be placed in front of <template></template>, not inside <script></script>
        - The following is the usage of common components in Quickapp:
        {component_usage}
        - Strictly follow the above tips to generate code, do not use it on your own.
    """
    return direct_prompt

def get_target_file_path(source_file_path):
    if (os.path.dirname(source_file_path).endswith('src')) :
        tartget_path = os.path.join(os.path.dirname(source_file_path), 'pages', 'home', 'index.ux')
    else:
        tartget_path = source_file_path.replace('vue', 'ux')
    tartget_path = tartget_path.replace('source_code', 'transformed_code')
    print(tartget_path)
    return tartget_path

def build_and_get_errors():
    if os.name == 'nt':
        return ""
    # Shell脚本的路径
    script_path = os.path.join(os.getcwd(), 'errors', 'build.sh')
    print(f"script_path\n{script_path}")

    if os.name == 'nt':  # 检测是否是Windows系统
    # 在Windows上，可以使用git-bash或其他兼容的Shell解释器
        command = ['C:\\Windows\\System32\\cmd.exe', script_path]
    else:
        # 在macOS和Linux上，可以直接执行
        command = [script_path]
    # 执行Shell脚本
    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    # 解析输出
    errors = [line for line in result.stderr.split('\n') if line.startswith('[ERROR]') or line.startswith('[WARN]')]

    # 打印错误信息
    for error in errors:
        print(error)

    # 检查脚本是否成功执行
    if result.returncode != 0:
        return ''
    
    return errors

def get_error_result(direct_code):
    filename = os.path.join(os.getcwd(), 'errors', 'template', 'src', 'pages', 'home', 'index.ux')
    if is_quickapp_code(direct_code):
        with open(filename, 'w', encoding='utf-8') as file:
            # 将代码写入文件
            file.write(direct_code)

        return build_and_get_errors()
    else: 
        return ""

def get_review_prompt(direct_code):
    error_result = get_error_result(direct_code)
    component_usage_path = './component_and_css_rules.txt'
    component_usage = read_txt(component_usage_path)
    review_prompt = f"""
        You are an expert of Quickapp(快应用) develoment and proficient in Quickapp development standards.
        The following is a piece of original Quickapp code generated by you. There may be some component writing or style usage that the Quickapp does not support.
        It will also provide error information when compiling a Quickapp project. Please use the error information and the knowledge you have learned about Quickapp development to identify code errors and correct them.
        Quickapp code:
        {direct_code}
        Error information:
        {error_result}
        The format of the Quickapp page is:
        <import name="xx" src="xx"></import>
        <template>
            <tags>
        </template>
        <script>
            export default {{
                data() {{
                    return {{}}
                }},
                xxx() {{}}
            }}
        </script>
        <style>
            css
        </style>
        - Note that tags and styles supported by Quickapp standards must be used. for example:
            （1）The <button> tag is not supported, instead use <input type="button"></input> instead.
            （2）The <button> tag is not supported, instead use <input type="button"></input> instead.
            （3）Text cannot be written directly inside <div></div>, but <text></text> should be used.
            （4）You cannot use <br> or \n for text line breaks. Instead, use multiple <text></text>.
            （5）<span> can only be used as a child component of <text>, <a> and <span>
            （6）Standards related to wechat miniprogram cannot appear. For example <view></view>
            （7）The standard of vue.js cannot appear. For example, Quickapp methods are at the same level as data, rather than appearing in methods.
            （8）CSS style length only supports px and % units, and does not support dp, rem, rpx and other units.
            （9）External styles can be introduced
            （10）Pay attention to converting the writing method of introducing custom components into vuejs into the writing method of introducing custom components into Quickapp:
                <import name="child" src="../components/child.ux"></import>
                <template>
                <div class="container">
                    <child></child>
                </div>
                </template>
                Pay attention, the above <import> statement needs to be placed in front of <template></template>, not inside <script></script>
        - The following is the usage of common components in Quickapp:
        {component_usage}
        - Strictly follow the above tips to generate code, do not use it on your own.
    """
    return review_prompt